<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item label="用户ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入用户手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="剩余咨询次数" prop="remainingConsultationFrequency">
        <el-input
          v-model="queryParams.remainingConsultationFrequency"
          placeholder="请输入剩余咨询次数（次数）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          type="number"
          min="0"
        />
      </el-form-item>
      <el-form-item label="会员类型" prop="memberId">
        <el-select v-model="queryParams.memberId" placeholder="会员状态" clearable class="!w-240px">
          <el-option
            v-for="i in membershipList"
            :key="i.id"
            :label="i.membershipName"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员有效期" prop="memberExpirationDate">
        <el-date-picker
          v-model="queryParams.memberExpirationDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="累计购买会员数量" prop="accumulatedQuantity">
        <el-input
          type="number"
          v-model="queryParams.accumulatedQuantity"
          placeholder="请输入累计购买会员数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          min="1"
        />
      </el-form-item>
      <el-form-item label="剩余报名次数" prop="remainingRegistrationsFrequency">
        <el-input
          v-model="queryParams.remainingRegistrationsFrequency"
          placeholder="请输入剩余报名次数（次数）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          type="number"
          min="0"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery"
          ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
        >
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['member:user:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['member:user:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="用户ID" align="center" prop="id" width="100px" />
      <el-table-column label="用户昵称" align="center" prop="nickname" width="180px" />
      <el-table-column label="用户手机号" align="center" prop="mobile" width="180px" />
      <el-table-column label="会员类型" align="center" prop="membershipName" width="100px">
        <template #default="{ row }">
          {{ row.membershipName || '非会员' }}
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="memberPurchaseDate" width="180px">
        <template #default="{ row }">
          <span v-if="row.memberPurchaseDate">
            {{ formatDate(row.memberPurchaseDate) }}-{{ formatDate(row.memberExpirationDate) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="累计购买会员数量"
        align="center"
        prop="accumulatedQuantity"
        width="180px"
      >
        <template #default="{ row }">
          {{ row.accumulatedQuantity || 0 }}
        </template>
      </el-table-column>
      <el-table-column
        label="剩余咨询次数（次数）"
        align="center"
        prop="remainingConsultationFrequency"
        width="180px"
      >
        <template #default="{ row }">
          {{ row.remainingConsultationFrequency || 0 }}
        </template>
      </el-table-column>
      <el-table-column
        label="剩余报名次数（次数）"
        align="center"
        prop="remainingRegistrationsFrequency"
        width="180px"
      >
        <template #default="{ row }">
          {{ row.remainingRegistrationsFrequency || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remakes" width="180px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="700px" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="$router.push('/user/detail/' + row.id)">
            查看详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="
              () => {
                currentUser = row
                remark = row.remakes
                showRemark = true
              }
            "
          >
            备注
          </el-button>
          <el-button link type="primary" @click="$router.push('/user/platform/' + row.id)">
            平台报名信息
          </el-button>
          <el-button link type="primary" @click="$router.push('/user/meeting/' + row.id)">
            会议报名信息
          </el-button>
          <el-button link type="primary" @click="$router.push('/user/order/' + row.id)">
            会员订单
          </el-button>
          <el-button
            link
            type="primary"
            @click="
              () => {
                currentUser = row
                setVipShow = true
              }
            "
          >
            设置会员信息
          </el-button>
          <el-button link type="primary" @click="$router.push('/user/actionLog/' + row.id)">
            操作日志
          </el-button>
          <el-button link type="primary" @click="$router.push('/user/collect/' + row.id)">
            收藏
          </el-button>
          <!-- <el-button link type="danger" @click="handleDelete(row.id)"> 删除 </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 备注 -->
  <el-dialog v-model="showRemark" width="500px" title="备注" center>
    <div>
      <el-input type="textarea" :rows="6" placeholder="请输入备注" resize="none" v-model="remark" />
      <div class="mt-20px"
        >最近更新时间：{{
          currentUser?.updateTime ? formatDate(currentUser?.updateTime as Date) : '-'
        }}</div
      >
    </div>
    <template #footer>
      <el-button @click="showRemark = false">取消</el-button>
      <el-button type="primary" @click="handleRemark">保存</el-button>
    </template>
  </el-dialog>

  <!-- 设置会员信息 -->
  <SetVip v-model="setVipShow" :currentUser="currentUser" @ok="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { UserApi, User } from '@/api/biz/user'
import { MembershipSettingsApi, MembershipSettings } from '@/api/biz/membershipsettings'
import SetVip from './components/SetVip.vue'

/** 会员用户 列表 */
defineOptions({ name: 'UserMember' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<User[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  mobile: undefined,
  password: undefined,
  status: undefined,
  registerIp: undefined,
  registerTerminal: undefined,
  loginIp: undefined,
  loginDate: [],
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: undefined,
  areaId: undefined,
  birthday: undefined,
  mark: undefined,
  point: undefined,
  tagIds: undefined,
  levelId: undefined,
  experience: undefined,
  groupId: undefined,
  createTime: [],
  memberId: undefined,
  memberExpirationDate: [],
  memberPurchaseDate: [],
  accumulatedQuantity: undefined,
  remakes: undefined,
  remainingConsultationFrequency: undefined,
  remainingRegistrationsFrequency: undefined,
  isMember: 0
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const currentUser = ref<User>() // 当前操作用户
const membershipList = ref<MembershipSettings[]>([]) // 会员列表
const setVipShow = ref(false) // 设置会员信息弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getMembershipList = async () => {
  const data = await MembershipSettingsApi.getMembershipSettingsPage({ pageNo: 1, pageSize: 100 })
  membershipList.value = data.list
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 备注
const showRemark = ref(false)
const remark = ref('')
const handleRemark = async () => {
  if (!remark.value) return message.warning('请输入备注内容')
  try {
    await UserApi.updateRemark({ id: currentUser.value?.id as number, remakes: remark.value })
    message.success(t('common.updateSuccess'))
    getList()
    showRemark.value = false
  } catch {}
}

// 修改状态
const handleStatusChange = async (row: User, status: number) => {
  try {
    await UserApi.updateStatus({ id: row.id, status })
    row.status = status
    message.success(t('common.updateSuccess'))
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除会员用户 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UserApi.deleteUserList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: User[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '会员用户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onActivated(() => {
  getList()
  getMembershipList()
})
</script>
